package buildcode.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Optional;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import buildcode.Context;
import buildcode.language.Type;
import buildcode.language.java.field.JavaField;

public class CommonUtil {

    public static String currentDate(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }

    public static String firstUpper(String name) {
        if (StringUtils.isNotBlank(name)) {
            return name.substring(0, 1).toUpperCase() + name.substring(1);
        }
        return name;
    }

    public static String firstLower(String name) {
        if (StringUtils.isNotBlank(name)) {
            return name.substring(0, 1).toLowerCase() + name.substring(1);
        }
        return name;
    }

    public static boolean isNeedImport(JavaField field, String contextPackage) {
        if (field == null || (field.getType().getPackagePath().contains("java.lang") || field.getType().getPackagePath().equals(contextPackage))) {
            return false;
        }
        return true;
    }

    public static void write(Type entity, String srcLocation, String tpl, String fileSuffix) {
        String packagePath = Optional.ofNullable(entity.getPackagePath()).map(v -> v.replace(".", File.separator) + File.separator).orElse("");
        String path = srcLocation + File.separator + packagePath + entity.getTypeName() + "." + fileSuffix;
        System.out.println(path);
        String classStr = VelocityUtil.render(tpl, entity, Context.getVelocityTools());
        System.out.println(classStr);
        File file = new File(path);
        try {
            if (!file.exists()) {
                FileUtils.forceMkdirParent(file);
                file.createNewFile();
                IOUtils.write(classStr, new FileOutputStream(file), "utf-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
